//
//  DataBaseManager.m
//  IntelligentHousehold
//
//  Created by wmwMAC on 17/6/20.
//  Copyright © 2017年 Cassie. All rights reserved.
//

#import "DataBaseManager.h"

@implementation DataBaseManager

+ (DataBaseManager *)shareInstance{
    static DataBaseManager *dbManager = nil;
    if (!dbManager) {
        dbManager = [[DataBaseManager alloc] init];
    }
    return dbManager;
}

-(void)openDB{
    NSString *path = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).lastObject;
    NSLog(@"%@",path);
    // 数据库路径
    NSString *dbPath = [path stringByAppendingPathComponent:@"DLS151233.db"];
    self.db = [FMDatabase databaseWithPath:dbPath];
    BOOL r = [_db open];
    if (r) {
        NSLog(@"打开成功");
    }else{
        NSLog(@"打开失败");
    }
    
}
// 干掉表
-(void)dropTable{
    NSString *drobSQL = @"DROP TABLE DLS151233";
    [self execSQL:drobSQL mes:@"删除表"];
}
//创建表
- (void)createTable{
    NSString *createSQL = @"CREATE TABLE IF NOT EXISTS DLS151233 (tel TEXT, time TEXT PRIMARY KEY)";
    [self execSQL:createSQL mes:@"创建表"];
}
-(BOOL)insertTel:(NSString *)tel Time:(NSString *)time{
    NSString *insertSQL = [NSString stringWithFormat:@"INSERT INTO DLS151233(tel,time) VALUES('%@', '%@')",tel,time];
    //    [self execSQL:insertSQL mes:@"插入"];
#warning 1 插入时判断
    // 通过插入判断
    BOOL r = [_db executeUpdate:insertSQL];
    if (r) {
        NSLog(@"INSERT 成功");
    }else{
        NSLog(@"INSERT 失败");
    }
    return r;
}
// 通过查询判断 (Query 询问)
-(BOOL)selectMovieById:(NSString *)mId{
    NSString *selectSQL = [NSString stringWithFormat:@"SELECT * FROM DLS151233 WHERE id = '%@'", mId];
    FMResultSet *set = [_db executeQuery:selectSQL];
    BOOL r = [set next];
    return r;
}

-(NSMutableArray *)selectAll{
    NSMutableArray *mArr = [NSMutableArray array];
    NSString *selectSQL = @"SELECT * FROM DLS151233";
    FMResultSet *set = [_db executeQuery:selectSQL];
    
    
    
    while ([set next]) {

        NSMutableDictionary *tempDic = [NSMutableDictionary dictionary];
        [tempDic setObject:[set stringForColumn:@"time"] forKey:@"time"];
        [tempDic setObject:[set stringForColumn:@"tel"] forKey:@"mtell"];
        
        [mArr addObject:tempDic];
        
    }
    return mArr;
}
-(void)deleteMovieById:(NSString *)mId{
    NSString *deleteSQL = [NSString stringWithFormat:@"DELETE FROM DLS151233 WHERE  id = '%@'", mId];
    [self execSQL:deleteSQL mes:@"DELETE"];
}

// 执行封装
-(void)execSQL:(NSString *)sql mes:(NSString *)mes{
    BOOL r = [_db executeUpdate:sql];
    if (r) {
        NSLog(@"%@ 成功",mes);
    }else{
        NSLog(@"%@ 失败",mes);
    }
}
@end
